package com.taomus.mytools.helper;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.List;

import org.junit.Test;

public class CommandUtils {

	public static String getOSName() {
		return System.getProperty("os.name");
	}

	@Test
	public void t() {
		System.out.print(getOSName());
	}
	
	public static Object getMethodValue(Object obj, String method) {
		if (obj != null) {
			Type type = obj.getClass().getGenericSuperclass();
			String pkName = type.toString().replace("class", "").trim();
			try {
				Class<?> cl = Thread.currentThread().getContextClassLoader()
						.loadClass(pkName);
				return cl.getMethod(method).invoke(obj);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void removeNull(Object obj) {
		try {
			if (obj instanceof List) {
				List<?> src = (List<?>) obj;
				if (src != null && src.size() > 0 && !src.isEmpty()) {
					Object one = src.get(0);
					Type type = one.getClass().getGenericSuperclass();
					Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(type.toString().replace("class ",""));
				/*	Class<?> cl = ClassLoader.getSystemClassLoader()
							.loadClass(type.toString().replace("class ",""));*/
					for (int i = 0; i < src.size(); i++) {
						obj = src.get(i);
						Field[] fs = cl.getDeclaredFields();
						int count = 0;
						int index = i;
						for (Field f : fs) {
							f.setAccessible(true);
						/*	if (f.getType().equals(List.class)) {
								List<?> two = (List<?>)f.get(one);
								removeNull(two);
							}*/
							if (f.get(obj) == null) {
								count++;
							}
						}
						if (count > fs.length/2) {
							src.remove(index);
						}
					}
				}
			}
		} catch (Exception e) {

		}
	}

	/**
	 * 
	 * @param src
	 *            List集合
	 * @param cl
	 *            集合类型
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public static <T> void print(Object obj)
			throws IllegalArgumentException, IllegalAccessException,
			ClassNotFoundException {
		try {
			if (obj instanceof List) {
				List<?> src = (List<?>) obj;
				if (src != null && src.size() > 0 && !src.isEmpty()) {
					Object one = src.get(0);
					Type type = one.getClass().getGenericSuperclass();
					Class<?> cl = ClassLoader.getSystemClassLoader()
							.loadClass(type.toString().replace("class ",""));
					for (int i = 0; i < src.size(); i++) {
						obj = src.get(i);
						Field[] fs = cl.getDeclaredFields();
						int count = 0;
						int index = i;
						for (Field f : fs) {
							f.setAccessible(true);
							System.out.println(f.getName() +":"+f.get(obj));
						}
						if (count == 1) {
							src.remove(index);
						}
					}
				}
			}
		} catch (Exception e) {

		}
	}
}
